package com.cqjtu.education.utils;

import com.sun.mail.util.MailSSLSocketFactory;
import org.springframework.stereotype.Component;
import org.springframework.beans.factory.annotation.Value;

import javax.mail.*;
import javax.mail.internet.InternetAddress;
import javax.mail.internet.MimeBodyPart;
import javax.mail.internet.MimeMessage;
import javax.mail.internet.MimeMultipart;
import java.security.GeneralSecurityException;
import java.util.Properties;

/***
 * @title EmailUtil
 * @description <write your description>
 * @author 冉鹏
 * @create 2022/10/26 16:38
 **/
@Component
public class EmailUtil {
    @Value("${spring.mail.username}")
    private String username;

    @Value("${spring.mail.password}")
    private String password;

    @Value("${spring.mail.host}")
    private String host;

    @Value("${spring.mail.port}")
    private String port;


    /**
     * 发送邮件
     *
     * @param code    验证码
     * @param toEmail 收件人邮箱（例：12345678@qq.com）
     */
    public void sendEmail(String toEmail, String code) {
        Transport transport = null;
        // 获取系统属性
        Properties properties = System.getProperties();
        // 设置邮件服务器
        properties.setProperty("mail.smtp.host", host);
        //企业邮箱发送
        properties.setProperty("mail.transport.protocol", "smtp");
        properties.setProperty("mail.smtp.socketFactory.class", "javax.net.ssl.SSLSocketFactory");
        properties.setProperty("mail.smtp.port", port);
        //设置启用smtp身份验证
        properties.setProperty("mail.smtp.auth", "true");
        MailSSLSocketFactory sf = null;
        try {
            sf = new MailSSLSocketFactory();
            sf.setTrustAllHosts(true);
        } catch (GeneralSecurityException e) {
            e.printStackTrace();
        }
        properties.put("mail.smtp.ssl.enable", "true");
        properties.put("mail.smtp.ssl.socketFactory", sf);
        properties.put("mail.smtp.socketFactory.fallback", "false");
        properties.put("mail.smtp.socketFactory.port", port);
        // 获取默认session对象
        Session session = Session.getDefaultInstance(properties, new Authenticator() {
            @Override
            public PasswordAuthentication getPasswordAuthentication() {
                return new PasswordAuthentication(username, password); //发件人邮件、授权码
            }
        });
        try {
            //创建默认的 MimeMessage 对象。
            MimeMessage message = new MimeMessage(session);
            //Set From: 头部头字段
            message.setFrom(new InternetAddress(username));
            // Set To: 头部头字段
            message.addRecipient(Message.RecipientType.TO,
                    new InternetAddress(toEmail));
            //Set Subject: 头字段
            message.setSubject("邮箱验证码");
            //向multipart对象中添加邮件的各个部分内容，包括文本内容和附件
            Multipart multipart = new MimeMultipart();
            //设置邮件的文本内容
            BodyPart contentPart = new MimeBodyPart();
            contentPart.setText("您的验证码为" + code + "，该验证码5分钟内有效，请勿泄露于他人。");
            multipart.addBodyPart(contentPart);
            //将multipart对象放到message中
            message.setContent(multipart);
            //保存邮件
            message.saveChanges();
            //发送消息
            javax.mail.Transport.send(message, message.getAllRecipients());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

}
